<?php

namespace app\admin\model\article;

use app\admin\model\UserCollection;
use think\Model;


class Works extends Model
{

    

    

    // 表名
    protected $name = 'works';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }



    public function category()
    {
        return $this->belongsTo('app\admin\model\user\TeacherCategory', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getList($condition, $is_paginate = 0,$limit = 15){
        $list = $this->where($condition)
            ->where("switch" , 1)
            ->order("weigh","desc");
        if($is_paginate){
            $list = $list->paginate();
        }else{
            $list = $list->limit($limit)->select();
        }
        foreach ($list as $key => &$value){
            $value = $this->dealInfo($value);
        }
        return $list;
    }

    public function getInfo($condition,$user=null){
        $info = $this->where($condition)
            ->order("weigh","desc")
            ->find();
        if(!$info){
            exception("未找到作品");
        }
        $info = $this->dealInfo($info);
        $userCollectionModel = new UserCollection();
        $info["is_collection"] = $userCollectionModel->checkUserCollection($user,$info['id'],$userCollectionModel::TYPE_WORKS);
        return $info;
    }

    public function dealInfo($info){
        $images = [];
        if($info['images']){
            $images = explode(",",$info['images']);
            foreach ($images as $iK => &$iV){
                $iV = deal_img_url($iV);
            }
        }
        $info['images'] = $images;
        return $info;
    }
}
